package com.drojian.page4;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.drojian.demo.R;

import java.util.List;

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
    private  List<Data> listData;
    public DataAdapter(List<Data> listData) {
       this.listData = listData;
    }
     class ViewHolder extends RecyclerView.ViewHolder{
        TextView id;
        TextView name;
        CheckBox checkBox;
        Button deleteButton;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            id = itemView.findViewById(R.id.id);
            name = itemView.findViewById(R.id.name);
            checkBox = itemView.findViewById(R.id.checkbox);
            deleteButton = itemView.findViewById(R.id.delete_button);
            checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Data data = listData.get(getAdapterPosition());
                    data.setSelected(!data.isSelected());
                    notifyDataSetChanged(); // 更新选中状态
                    checkBox.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    });
                }
            });

            deleteButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    if(position != RecyclerView.NO_POSITION){
                            Data data = listData.get(position);
                             listData.remove(position);
                             notifyItemRemoved(position);//移除对应视图项
                             Toast.makeText(v.getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.data_layout, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Data data = listData.get(position);
        holder.id.setText(String.valueOf(data.getId()));
        holder.name.setText(data.getName());
        holder.checkBox.setChecked(data.isSelected()); // 设置选中状态
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

}
